import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AlertController } from '@ionic/angular';
import { register } from '../api/request';

@Component({
  selector: 'app-page-register',
  templateUrl: './page-register.component.html',
  styleUrls: ['./page-register.component.scss']
})
export class PageRegisterComponent {

  constructor(private router: Router, private alertController: AlertController) { }

  username: string = ""

  level: string = ""

  sex: string = ""

  age: string = ""

  password: string = ""

  confirm: string = ""

  async submitRig() {
    // valid
    if (this.username === "" || this.level === "" || this.sex === "" || this.age === "" || this.password === "" || this.confirm === "") {
      const alert = await this.alertController.create({
        header: '请输入每一项',
        message: '请输入每一项',
        buttons: ['OK'],
      });
      await alert.present();
      return
    }
    if (this.password !== this.confirm) {
      const alert = await this.alertController.create({
        header: '密码不一致',
        message: '两次密码不一致',
        buttons: ['OK'],
      });
      await alert.present();
      return
    }

    // 注册
    const data = {
      level: this.level,
      sex: this.sex,
      age: Number(this.age),
      nickname: this.username
    }
    register(this.username, this.password, data).then(async res => {
      const alert = await this.alertController.create({
        header: '成功',
        message: '您已经成功注册，请登录！',
        buttons: [{
          text: "OK",
          handler: () => {
            this.goLoginPage()
          }
        }],
      });
      await alert.present();
    }).catch(async e => {
      const alert = await this.alertController.create({
        header: '用户名重复',
        message: '用户名已被注册，请重新输入',
        buttons: ['OK'],
      });
      await alert.present();
      this.username = ""
    })

  }

  goLoginPage() {
    this.router.navigate(['/starnight-student/login'])
  }

}
